use axum::Json;
use com::{ code, sea_orm::connect, process, query };
use migration::{Migrator, MigratorTrait};
use sea_orm::query::*;
// 应用所有挂起的迁移
pub(super) async fn up() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::up(&conn, None).await )
}
// 回滚上次应用的迁移
pub(super) async fn down() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::down(&conn, None).await )
}
// 从数据库中删除所有表，然后重新应用所有迁移
pub(super) async fn fresh() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::fresh(&conn ).await )
}
// 回滚所有已应用的迁移，然后重新应用所有迁移
pub(super) async fn refresh() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::refresh(&conn ).await )
}
// 回滚所有应用的迁移
pub(super) async fn reset() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::reset(&conn ).await )
}
// 在数据库中创建迁移表 seaql_migrations
pub(super) async fn install() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let conn = connect().await?;
    code::send_ok(Migrator::install(&conn).await )
}
// 生成 Entity
pub(super) async fn entity() -> Result<Json<JsonValue>, Json<JsonValue>>{
    let order = "sea-orm-cli generate entity -o ../entity --lib";
    process::cmd_spawn(&order).await
}
// 在数据库中创建迁移表 seaql_migrations
pub(super) async fn generate(Json(body):Json<JsonValue>) -> Result<Json<JsonValue>, Json<JsonValue>>{
    let name = query::str(&body, "name").unwrap_or_default();
    if name.contains("-") { 
        return code::err("名称不能包含 -")
    }
    let order = "sea-orm-cli migrate generate ".to_string() + &name;
    process::cmd_spawn(&order).await
}
// 安装 sea-orm-cli
pub(super) async fn cli(Json(body):Json<JsonValue>) -> Result<Json<JsonValue>, Json<JsonValue>>{
    let name = query::str(&body, "name").unwrap_or_default();
    let order = "cargo install sea-orm-cli --no-default-features --features ".to_string() + &name;
    process::cmd_spawn(&order).await
}